//
//  MineController.m
//  FactorySale
//
//  Created by 胡小康 on 2020/4/21.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "MineController.h"
#import "CooperationProductCell.h"// 合作产品cell
#import "TableSectionHeaderView.h"// 表区头
#import "ProductController.h"// 点击合作产品进入的控制器
#import "LeiJiXiaoShouEViewController.h"// 累计销售额控制器
#import "ProductOperationController.h"// 申请产品候保二维码控制器
#import "FactoryInfoDetailModel.h"// 用户信息model
#import "CumulativeSalesCell.h" // 我的首页的累计销售额cell
#import "CooperationProductModel.h"// 合作产品model
#import "EditMyInfoViewController.h"// 编辑资料控制器
#import "SettingViewController.h"// 设置
#import "BankCardManageViewController.h"// 银行卡管理
#import "MyClientController.h"// 我的客户
#import "SYBigImage.h"
#import "GrantBillListController.h"// 发放补助金账单
#import "MyAccountController.h"// 我的账户
@interface MineController ()<UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topNavBarConstraint;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;// 头像
@property (weak, nonatomic) IBOutlet UILabel *companyNameLabel;// 公司名称
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;// 电话
@property (weak, nonatomic) IBOutlet UIButton *editButton;// 编辑信息按钮

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;// 地址
@property (weak, nonatomic) IBOutlet UILabel *accountNameLabel;// 户名
@property (weak, nonatomic) IBOutlet UILabel *bankLabel;// 银行
@property (weak, nonatomic) IBOutlet UILabel *paymentAccountLabel;// 收款账号
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) FactoryInfoDetailModel *detailModel;// 信息详情model
@property (nonatomic,strong) FactoryInfoBankCardListModel *bankModel;// 银行卡信息model
@property (nonatomic,strong) CooperationProductModel *productModel;// 产品model
@property (nonatomic,strong)NSMutableArray <CooperationProductModel *>*productModelArray;
@property (nonatomic,strong) NSMutableArray *isExpandArray;// 存储展开闭合状态的数组
@end

@implementation MineController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self requestUserInfoData];
    [self requestCooperationProductDataList];
}

//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:NO animated:animated];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topNavBarConstraint.constant = kNaviHeight;
    
    [self setupUI];
    //ShowToastWithText(@"加载中");
    self.productModelArray = [NSMutableArray arrayWithCapacity:0];
    self.isExpandArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i<4; i++) {
        [self.isExpandArray addObject:@"0"];//0:没展开 1:展开
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
//获取厂家所有的产品
- (void)requestCooperationProductDataList{
    
    [NetWorkTool POST:getFactoryParts param:nil success:^(id dic) {
        //NSLog(@"获取厂家所有的产品 %@",dic);
        self.productModelArray = [CooperationProductModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.tableView reloadData];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}

// 请求数据，给顶部资料控件赋值
- (void)requestUserInfoData {
    
    [NetWorkTool POST:getFactoryInfo param:nil success:^(id dic) {
        
        self.detailModel = [FactoryInfoDetailModel mj_objectWithKeyValues:dic[@"data"]];
        self.bankModel = [FactoryInfoBankCardListModel mj_objectWithKeyValues:dic[@"data"][@"bankCard"]];
        
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.detailModel.factory_img] placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];
        SYBigImage * bigI = [[SYBigImage alloc]init];
        self.headImageView.userInteractionEnabled = YES;
        [self.headImageView addGestureRecognizer:bigI];
        
        self.companyNameLabel.text = self.detailModel.factory_name;
        self.companyNameLabel.adjustsFontSizeToFitWidth = YES;
        self.phoneLabel.text = self.detailModel.factory_phone;
        self.addressLabel.text = self.detailModel.factory_address;
        self.accountNameLabel.text = self.bankModel.user_name;
        self.bankLabel.text = self.bankModel.bank_name;
        self.paymentAccountLabel.text = [self returnBankCard:self.bankModel.card_no];
        
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}

//这是处理银行卡号明文字符串的方法，只需要将明文的银行卡号传入下面的API接口就行
-(NSString *)returnBankCard:(NSString *)BankCardStr {
    NSString *formerStr = [BankCardStr substringToIndex:4];
    NSString *str1 = [BankCardStr stringByReplacingOccurrencesOfString:formerStr withString:@""];
    NSString *endStr = [BankCardStr substringFromIndex:BankCardStr.length-4];
    NSString *str2 = [str1 stringByReplacingOccurrencesOfString:endStr withString:@""];
    NSString *middleStr = [str2 stringByReplacingOccurrencesOfString:str2 withString:@"****"];
    NSString *CardNumberStr = [formerStr stringByAppendingFormat:@"%@%@",middleStr,endStr];
    return CardNumberStr;
}

- (void)setupUI {
    
    self.headImageView.layer.borderColor = WHITECOLOR.CGColor;
    self.headImageView.layer.borderWidth = 1;
    
    self.editButton.layer.borderWidth = 0.5;
    self.editButton.layer.borderColor = [UIColor colorWithHexString:@"#FFFFFF"].CGColor;
    self.tableView.rowHeight = 50;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
}

#pragma mark -- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    TableSectionHeaderView * headerView = [[TableSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    

    if (section == 0) {
        headerView.logoImgView.image = [UIImage imageNamed:@"我的账户"];
        headerView.titleLab.text = @"我的账户";
        headerView.arrowImageView.image = [UIImage imageNamed:@"grayRightArrow"];
        [headerView.arrowImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.offset(15);
            make.right.offset(-20);
            make.bottom.offset(-15);
            make.width.offset(15);
        }];
    } else if (section == 1) {
        headerView.logoImgView.image = [UIImage imageNamed:@"合作产品"];
        headerView.titleLab.text = @"合作产品";
    } else if (section == 2){
        headerView.logoImgView.image = [UIImage imageNamed:@"销售额及返点"];
        headerView.titleLab.text = @"销售额";
    } else if (section == 3) {
        headerView.logoImgView.image = [UIImage imageNamed:@"客户管理"];
        headerView.titleLab.text = @"客户管理";
    } else{
        headerView.logoImgView.image = [UIImage imageNamed:@"发放补助金账单"];
        headerView.titleLab.text = @"发放补助金账单";
        headerView.arrowImageView.image = [UIImage imageNamed:@"grayRightArrow"];
        [headerView.arrowImageView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.offset(15);
            make.right.offset(-20);
            make.bottom.offset(-15);
            make.width.offset(15);
        }];
    }
    if (section < 4 && section > 0) {
        if ([_isExpandArray[section] isEqualToString:@"0"]) {
            //未展开
            headerView.arrowImageView.image = [UIImage imageNamed:@"向下"];
        } else {
            //展开
            headerView.arrowImageView.image = [UIImage imageNamed:@"向上"];
        }
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.delegate = self;
    [headerView addGestureRecognizer:tap];
    headerView.tag = section;
    return headerView;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    } else if (section == 1) {
        if ([self.isExpandArray[section]isEqualToString:@"1"]) {
            return self.productModelArray.count;;
        }else{
            return 0;
        }
    } else if (section == 2) {
        if ([self.isExpandArray[section]isEqualToString:@"1"]) {
            return 2;
        }else{
            return 0;
        }
    } else if (section == 3) {
        if ([self.isExpandArray[section]isEqualToString:@"1"]) {
            return 1;
        }else{
            return 0;
        }
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {// 合作产品
        CooperationProductCell *cell = [CooperationProductCell cellWithTableView:tableView];
        cell.model = self.productModelArray[indexPath.row];
        return cell;
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            CumulativeSalesCell *cell = [CumulativeSalesCell cellWithTableView:tableView];
            if ([self.detailModel.saleAmount isEqualToString:@"0"]) {
                cell.cumulativeSalesLabel.text = [NSString stringWithFormat:@"￥%@",@"0.00"];
            } else {
                cell.cumulativeSalesLabel.text = [NSString stringWithFormat:@"￥%@",self.detailModel.saleAmount];
            }
            return cell;
        } else {
            CooperationProductCell *cell = [CooperationProductCell cellWithTableView:tableView];
            if (indexPath.row == 1) {
                cell.titleLabel.text = @"申请产品候保二维码";
            }
            return cell;
        }
    } else {
        CooperationProductCell *cell = [CooperationProductCell cellWithTableView:tableView];
        cell.titleLabel.text = @"我的客户";
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {// 合作产品
        
        ProductController * vc = [[ProductController alloc]init];
        vc.model = self.productModelArray[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (indexPath.section == 2 && indexPath.row == 0) {
        // 累计销售额
        LeiJiXiaoShouEViewController *vc = [[LeiJiXiaoShouEViewController alloc]init];
        vc.leiJiMoney = [NSString stringWithFormat:@"%@元",self.detailModel.saleAmount];
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 2 && indexPath.row == 1){
        // 申请产品候保二维码
        ProductOperationController * vc = [[ProductOperationController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        // 我的客户
        MyClientController * vc = [[MyClientController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

// 设置
- (IBAction)setupButtonClick:(UIButton *)sender {
    SettingViewController *vc = [[SettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 编辑资料
- (IBAction)editDataButtonClick:(UIButton *)sender {
    EditMyInfoViewController *vc = [[EditMyInfoViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 银行卡信息
- (IBAction)bankCardBgButtonClick:(UIButton *)sender {
    BankCardManageViewController *vc = [[BankCardManageViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    if (tap.view.tag == 0) {// 我的账户
        MyAccountController * vc = [[MyAccountController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else if (tap.view.tag == 4) {
        // 发放补助金账单
        GrantBillListController * vc = [[GrantBillListController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        if ([_isExpandArray[tap.view.tag] isEqualToString:@"0"]) {
            //关闭 => 展开
               [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"1"];
        } else {
            //展开 => 关闭
               [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"0"];
        }
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:tap.view.tag];
        [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
    }
    
}

@end
